#!/usr/bin/ruby
# Copyright 2011, Dell
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 

require 'rubygems'
require 'json'
require 'getoptlong'

#
# Parsing options can be added by adding to this list before calling opt_parse
# 
@options = [
    [ [ '--help', '-h', GetoptLong::NO_ARGUMENT ], "--help or -h - help" ],
    [ [ '--attribute', '-a', GetoptLong::REQUIRED_ARGUMENT ], "--attribute <attribute> or -a <attribute>  - Name of hash object to return.  Use . as sub-hash delimiter" ]
]

@attributes = []


def usage (rc)
  puts "Usage: parse_node_data [options] [filename]"
  @options.each do |options|
    puts "  #{options[1]}"
  end
  exit rc
end

def help
  usage 0
end


### Start MAIN ###

def opt_parse()
  sub_options = @options.map { |x| x[0] }
  lsub_options = @options.map { |x| [ x[0][0], x[2] ] }
  opts = GetoptLong.new(*sub_options)

  opts.each do |opt, arg|
    case opt
      when '--help'
        usage 0
      when '--attribute'
        @attributes << arg
      else
        usage -1
    end
  end

  if ARGV.length > 1
    usage -1
  end
end

def main()
  opt_parse
  
  if (ARGV.length == 1)
    file = File.open(ARGV[0])
  else
    file = STDIN
  end
  hash = JSON.parse(file.read)

  @attributes.each do |attr|
    data = hash
    fields = attr.split(".") 
    fields.each { |x| data = data[x] unless data.nil? }

    puts "#{attr}=#{data}"
  end

end

main

